package com.iqilu.ksd.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.adapter.CommentAdapter;
import com.iqilu.ksd.bean.CommentBean;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.KeyboardUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.jaeger.library.StatusBarUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Coofee on 2016/11/4.
 */

public class CommentActivity extends BaseActivity {

    private static final String TAG = "CommentActivity";

    private UserBean user;
    private ArrayList<CommentBean> list;
    private int articleid;
    private int catid;
    private String type;
    private int page = 1;
    private CommentAdapter adapter;
    private LigDialog ligDialog;

    private XRefreshView xRefreshView;
    private RecyclerView rvList;
    private ImageView imgEmpty;
    private RelativeLayout layLoading;
    private TextView btSend;
    private EditText etContent;

    private static final int CODE_LOGIN = 1001;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        user = ((MyApplication) getApplication()).getUser();
        Intent intent = getIntent();
        articleid = intent.getIntExtra("articleid", 0);
        catid = intent.getIntExtra("catid", 0);
        type = intent.getStringExtra("type");
        initView();
        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.enableReleaseToLoadMore(true);
        xRefreshView.enableRecyclerViewPullUp(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                super.onRefresh();
                page = 1;
                getList();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page++;
                getList();
            }
        });
        adapter = new CommentAdapter(this);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(this));
        rvList.setAdapter(adapter);
        page = 1;
        getList();
    }

    private void initView() {
        xRefreshView = getView(R.id.xRefreshView);
        rvList = getView(R.id.rv_list);
        rvList.setHasFixedSize(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvList.setLayoutManager(layoutManager);
        imgEmpty = getView(R.id.img_empty);
        btSend = getView(R.id.bt_send);
        etContent = getView(R.id.et_content);
        layLoading = getView(R.id.lay_loading);
        layLoading.setVisibility(View.VISIBLE);

        btSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toSubmit();
            }
        });
    }

    private void toSubmit() {
        if (user == null || user.getId() < 1) {
            startActivityForResult((new Intent(this, LoginActivity.class)), CODE_LOGIN);
            return;
        }

        String content = etContent.getText().toString();
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(CommentActivity.this, R.string.comment_content_empty, Toast.LENGTH_SHORT).show();
        } else {
            submitComment(content);
        }

    }

    private void afterRefresh() {
        if (page == 1) {
            imgEmpty.setVisibility(View.VISIBLE);
            xRefreshView.stopRefresh();
        } else {
            xRefreshView.stopLoadMore();
        }
        layLoading.setVisibility(View.GONE);
    }

    private void afterSubmit() {
        etContent.setText("");
        KeyboardUtils.hideSoftInput(this);
        if (page == 1) {
            xRefreshView.startRefresh();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            user = ((MyApplication) getApplication()).getUser();
        }
    }

    private void getList() {
        String url = Api.URL_COMMENT + "?articleid=" + articleid + "&catid=" + catid + "&type=" + type + "&page=" + page;
        Log.i(TAG, "url=" + url);
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                afterRefresh();
                if (page == 1) {
                    xRefreshView.setVisibility(View.GONE);
                    imgEmpty.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onResponse(String response, int id) {
                afterRefresh();
                ArrayList<CommentBean> result = null;
                result = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<CommentBean>>() {
                });
                if (page == 1) {
                    if (result == null || result.size() == 0) {
                        xRefreshView.setVisibility(View.GONE);
                        imgEmpty.setVisibility(View.VISIBLE);
                    } else {
                        imgEmpty.setVisibility(View.GONE);
                        list = result;
                    }
                } else {
                    if (result == null || result.size() == 0) {
                        Toast.makeText(CommentActivity.this, R.string.list_not_have, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    list.addAll(result);
                }
                adapter.setData(list);
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void submitComment(String comment) {
        String url = Api.URL_COMMENT;
        OkHttpUtils
                .post()
                .url(url)
                .addParams("articleid", "" + articleid)
                .addParams("catid", "" + catid)
                .addParams("type", "" + type)
                .addParams("comment", "" + Uri.encode(comment))
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        ligDialog = new LigDialog(CommentActivity.this, getString(R.string.waiting));
                        ligDialog.show();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ligDialog.dismiss();
                        Toast.makeText(CommentActivity.this, R.string.comment_add_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ligDialog.dismiss();
                        int status = 0;
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            status = jsonObject.getInt("status");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (status == 1) {
                            afterSubmit();
                            Toast.makeText(CommentActivity.this, R.string.comment_add_success, Toast.LENGTH_SHORT).show();
//                            xRefreshView.startRefresh();
                        } else {
                            Toast.makeText(CommentActivity.this, R.string.comment_add_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
}
